package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IProductTypeDAO;
import org.jsola.hr.dto.ProductTypeAddDTO;
import org.jsola.hr.dto.ProductTypeUpdateDTO;
import org.jsola.hr.entity.ProductDO;
import org.jsola.hr.entity.ProductTypeDO;
import org.jsola.hr.query.ProductTypeQuery;
import org.jsola.hr.service.IProductService;
import org.jsola.hr.service.IProductTypeService;
import org.jsola.hr.vo.ProductTypeListVO;
import org.jsola.hr.vo.ProductTypeVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品分类
 *
 * @author zhr
 */
@Service("hrProductTypeServiceImpl")
public class ProductTypeServiceImpl implements IProductTypeService {

    @Autowired
    private IProductTypeDAO productTypeDAO;

    @Autowired
    private IProductService productService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public ProductTypeVO save(ProductTypeAddDTO productTypeAddDTO, TokenUser tokenUser) {
        // 查询租户下所有产品
        List<ProductTypeDO> productTypeDOList = selectBySite(tokenUser.getSiteId());
        ParamException.isFalse(productTypeDOList.parallelStream().anyMatch(productTypeDO
                -> productTypeAddDTO.getProductTypeName().equals(productTypeDO.getProductTypeName())), "产品分类名称已存在");
        // 转DO
        ProductTypeDO productTypeDO = productTypeAddDTO.to(ProductTypeDO.class);
        // 保存
        productTypeDO = save(productTypeDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return productTypeDO.to(ProductTypeVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(ProductTypeUpdateDTO productTypeUpdateDTO, TokenUser tokenUser) {
        // 查询租户下所有产品
        List<ProductTypeDO> productTypeDOList = selectBySite(tokenUser.getSiteId());
        productTypeDOList = productTypeDOList.parallelStream().filter(productTypeDO
                -> !productTypeUpdateDTO.getId().equals(productTypeDO.getId())).collect(Collectors.toList());
        ParamException.isFalse(productTypeDOList.parallelStream().anyMatch(productTypeDO
                -> productTypeUpdateDTO.getProductTypeName().equals(productTypeDO.getProductTypeName())), "产品分类名称已存在");
        //转DO
        ProductTypeDO productTypeDO = productTypeUpdateDTO.to(ProductTypeDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(productTypeDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... productTypeIds) {
        // 查询分类下的产品信息 若存在 不允许删除
        List<ProductDO> productDOList = productService
                .selectDoByProductTypeIds(Arrays.asList(productTypeIds), tokenUser.getSiteId());
        ParamException.isTrue(CollectionUtils.isEmpty(productDOList), "产品分类下还存在产品，无法删除");
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) productTypeIds);
    }


    @Override
    public ProductTypeVO selectById(String productTypeId, String siteId) {
        ProductTypeDO productTypeDO = selectDOById(productTypeId, siteId);
        if (productTypeDO == null) {
            return null;
        }
        return productTypeDO.to(ProductTypeVO.class);
    }

    @Override
    public List<ProductTypeListVO> select(ProductTypeQuery productTypeQuery, String siteId) {
        List<ProductTypeDO> productTypeDOList = selectDO(productTypeQuery, siteId);
        if (CollectionUtils.isEmpty(productTypeDOList)) {
            return productTypeDOList == null ? null : new ArrayList<>();
        }
        return productTypeDOList.stream()
                .map(productTypeDO -> productTypeDO.to(ProductTypeListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(ProductTypeQuery productTypeQuery, String siteId) {
        Example example = buildExample(productTypeQuery, siteId);
        return productTypeDAO.selectCountByExample(example);
    }

    @Override
    public Page<ProductTypeListVO> selectPage(ProductTypeQuery productTypeQuery, String siteId) {
        Example example = buildExample(productTypeQuery, siteId);
        Page<ProductTypeDO> page = productTypeDAO.selectPageByExample(example,
                productTypeQuery.getPageNo(),
                productTypeQuery.getPageSize());

        return page.to(ProductTypeListVO.class);
    }

    @Override
    public ProductTypeDO selectDOById(String productTypeId, String siteId) {
        return listById(productTypeId, siteId);
    }

    @Override
    public List<ProductTypeDO> selectDO(ProductTypeQuery productTypeQuery, String siteId) {
        Example example = buildExample(productTypeQuery, siteId);
        return productTypeDAO.selectByExample(example);
    }

    @Override
    public List<ProductTypeDO> selectBySite(String siteId) {
        Example example = new Example(ProductTypeDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        example.orderBy("gmtCreate").desc();
        return productTypeDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example
     *
     * @param productTypeQuery 查询参数
     * @param siteId           所属站点id
     * @return example
     */
    private Example buildExample(ProductTypeQuery productTypeQuery, String siteId) {
        Example example = new Example(ProductTypeDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // 排序
        ExampleKit.setExampleOrder(example, productTypeQuery.getOrders());
        return example;
    }
}




